package com.fingard.dsp.bank.directbank.bozz02;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * 郑州银行批量代收付
 * 
 * @author Cruise
 * @date 2018/11/28
 */
public class BOZZ02BatPayRec extends BOZZ02Base implements IBatPayRec {
	@Override
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
		retAts.reqSeqID = p_req1988.reqBatchNO;
		
		try {
			StringBuilder sbFileContent = new StringBuilder();

			sbFileContent.append("付款人账号|收款人姓名|收款人账户|金额|转账类型(I-行内，D-行外)|收款行名称|汇款方式(N-普通，H-快速,F-实时)|用途|收款方开户行联行号(跨行必填)");
			while (p_req1988.readRecord()) {
				if (sbFileContent.length() > 0) {
					sbFileContent.append("\r\n");
				}
				
				String payAct = p_req1988.readedDetail.payAct;
				String recName = p_req1988.readedDetail.recName;
				String recAct = p_req1988.readedDetail.recAct;
				String payAmt = p_req1988.readedDetail.payAmount;
				String payType = "1".equals(p_req1988.readedDetail.sameBnk) ? "I" : "D";
				String recBankName = p_req1988.readedDetail.recBankName;
				String paySpdFlag = "1".equals(p_req1988.readedDetail.paySpd) ? "F" : "N";
				String usage = p_req1988.readedDetail.askNumber + "_" + p_req1988.readedDetail.useType;
				String cnapsCode = p_req1988.readedDetail.cnapsCode;
				
				// 明细信息:付款人账号|收款人账号|金额|转账类型|收款行名称|汇款方式|用途|收款方开户行联行号\r\n
				String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}", payAct, recName, recAct, payAmt, payType, recBankName, paySpdFlag, usage, cnapsCode);
				sbFileContent.append(tmpReqBodyDetail);
			}
			WriteBankLogLn2("本地批次明细文件内容:\r\n" + sbFileContent.toString());	
			
			String tmpUploadFileName = p_req1988.reqBatchNO + ".txt";
			String tmpLocalMarkPath = StringHelper.trimEnd(bankFront.bkPayFolder, File.separator) + File.separator + tmpUploadFileName;
			WriteBankLogLn2("批次文件存入本地路径:\r\n" + tmpLocalMarkPath);
			FileHelper.writeFile(tmpLocalMarkPath, sbFileContent);
			
			BOZZ02Header tmpBankHeader = new BOZZ02Header();
	        tmpBankHeader.trsCode = "B2EBatchTransfer|" + p_req1988.reqBatchNO;
	        tmpBankHeader.erpJnlNo = p_req1988.reqBatchNO;
	        tmpBankHeader.erpTrsTimestamp = Format.DateTimeFormat.format(p_req1988.getPayDateTime());
	        
	        XmlTextWriter xmlWriter = new XmlTextWriter();
	        writeCommonHead(xmlWriter, tmpBankHeader);
	        
	        xmlWriter.writeStartElement("Body");
	        xmlWriter.writeElementString("Filename", tmpUploadFileName);
	        xmlWriter.writeElementString("Transcode", "B2EBatchTransfer");
	        xmlWriter.writeEndDocument();
	        
			String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), "uploadFile", false, tmpUploadFileName, tmpBankHeader.trsCode,"1");
			
			if (tmpStrRet[0].length() == 0) {
				StringBuilder tmpSbMsg = new StringBuilder();
				XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
				if (tmpBkReader != null) {
					String tmpRespCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
					
					retAts.respCode = "0";
					retAts.respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
					retAts.transState = tmpRespCode;
					retAts.payInfoCode = tmpRespCode;
					
					String tmpBankBatchNo = tmpBkReader.getFirstText("/Message/Head/McJnlno");
					WriteBankLogLn2("本地批次流水映射文件内容: " + tmpBankBatchNo);
					String tmpSeqNoMapFilePath = getDataFileDirectory(p_req1988.getPayDateTime()) + File.separator + p_req1988.reqBatchNO + ".txt";
					FileHelper.writeFile(tmpSeqNoMapFilePath, tmpBankBatchNo, getCharset());
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpSbMsg.toString();
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL)) {
				retAts.respCode = "0";
				retAts.respInfo = tmpStrRet[1];
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = tmpStrRet[0];
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpStrRet[1];
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.toString();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetToATS();
		return retAts;
	}

	@Override
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
		retAts.reqSeqID = p_req1998.reqBatchNO;

		try {
			String tmpSeqNoMapFilePath = getDataFileDirectory(p_req1998.getBgnDateTime()) + File.separator + p_req1998.reqBatchNO + ".txt";
			String tmpBankBatchNo = FileHelper.readFileText(tmpSeqNoMapFilePath, getCharset());
			WriteBankLogLn2("本地批次流水映射文件内容: " + tmpBankBatchNo);
			if (StringHelper.hasAnyChar(tmpBankBatchNo)) {
				BOZZ02Header tmpBankHeader = new BOZZ02Header();
				tmpBankHeader.trsCode = "B2EBatchTransferQryDetail|" + p_req1998.reqBatchNO + "|" + tmpBankBatchNo;
		        tmpBankHeader.erpJnlNo = getQryTransID();
		        tmpBankHeader.erpTrsTimestamp = Format.DateTimeFormat.format(new Date());
		        
		        XmlTextWriter xmlWriter = new XmlTextWriter();
		        writeCommonHead(xmlWriter, tmpBankHeader);
		        xmlWriter.writeEndDocument();
		        
		        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), "downloadFile", false, p_req1998.reqBatchNO + ".txt", tmpBankHeader.trsCode,"1");
				
				if (tmpStrRet[0].length() == 0) {
	                StringBuilder tmpSbMsg = new StringBuilder();
	                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
	                if (tmpBkReader != null) {
	                	String tmpDownFileName = tmpBkReader.getFirstText("/transaction/success");
	                	if (StringHelper.hasAnyChar(tmpDownFileName)) {
	                		String tmpDownDate = Format.Date10Format.format(new Date());
	                		String tmpDownFilePath = StringHelper.trimEnd(bankFront.bkQryPayFolder, File.separator) + File.separator + tmpDownDate + File.separator + tmpDownFileName;
	                    	String tmpStrResp = FileHelper.readFileText(tmpDownFilePath, getCharset());
	                    	WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrResp);
	            			
	                    	if (StringHelper.hasAnyChar(tmpStrResp)) {
	                    		retAts.respCode = "0";
	                    		
	        					StringReader strReader = new StringReader(tmpStrResp);
	        					BufferedReader tmpReader = new BufferedReader(strReader);
	        					tmpReader.readLine();
	        					
	        					while(true) {
	        						String eachline = tmpReader.readLine();
	        						if(eachline == null){
	        							break;
	        						}
	        						if (eachline.indexOf("|") > 0) {
	        							String[] bodyValues = eachline.split("\\|");
	    								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
	    								
	    								tmpRetDetail.recAct = bodyValues[4];
	    								tmpRetDetail.recName = bodyValues[3];
	    								tmpRetDetail.postScript = bodyValues[12].split("_")[0];
	    								tmpRetDetail.payAmount = Format.DecimalAmtFormat.format(Double.parseDouble(bodyValues[5]));
	    								tmpRetDetail.result = bodyValues[13];
	    								tmpRetDetail.payInfoCode = bodyValues[13];
	    								tmpRetDetail.memo = bodyValues[13];
	    		                        
	    								retAts.writeRetDetail(tmpRetDetail);
	        						} else {
	        							retAts.respCode = "-1";
	        		            		retAts.respInfo = "银行返回明细数据格式非法!";
	        						}
	        					}
	                    	} else {
	                    		retAts.respCode = "-1";
	                    		retAts.respInfo = "本地批次结果文件内容为空!";
	                    	}
	                	} else {
	                		retAts.respCode = "-1";
	                		retAts.respInfo = tmpBkReader.getFirstText("/transaction/error");
	                	}
	                	
                        
                        
	                    /*String tmpRespCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
	                    if ("000000".equals(tmpRespCode)) {
	                    	retAts.respCode = "0";
	                    	String tmpDownFileName = tmpBkReader.getFirstText("/Message/Head/Filename");
	                    	String tmpDownFilePath = StringHelper.trimEnd(bankFront.bkQryPayFolder, File.separator) + File.separator + tmpDownFileName;
	                    	String tmpStrResp = FileHelper.readFileText(tmpDownFilePath, getCharset());
	                    	WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrResp);
	            			
	                    	if (StringHelper.hasAnyChar(tmpStrResp)) {
	        					StringReader strReader = new StringReader(tmpStrResp);
	        					BufferedReader tmpReader = new BufferedReader(strReader);
	        					tmpReader.readLine();
	        					
	        					while(true) {
	        						String eachline = tmpReader.readLine();
	        						if(eachline == null){
	        							break;
	        						}
	        						if (eachline.indexOf("|") > 0) {
	        							// 明细记录:交易流水|付款人名称|付款人账号|收款人账号|收款人名称|交易金额|备注|交易状态\n
	        							String[] bodyValues = eachline.split("\\|");
	    								RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
	    								
	    								tmpRetDetail.recAct = bodyValues[3];
	    								tmpRetDetail.recName = bodyValues[4];
	    								tmpRetDetail.postScript = bodyValues[6].split("_")[0];
	    								tmpRetDetail.payAmount = StringHelper.amountDivide100(bodyValues[5]);
	    								tmpRetDetail.result = bodyValues[7];
	    								tmpRetDetail.payInfoCode = bodyValues[7];
	    								tmpRetDetail.memo = bodyValues[7];
	    		                        
	    								retAts.writeRetDetail(tmpRetDetail);
	        						} else {
	        							retAts.respCode = "-1";
	        		            		retAts.respInfo = "银行返回明细数据格式非法!";
	        						}
	        					}
	                    	} else {
	                    		retAts.respCode = "-1";
	                    		retAts.respInfo = "本地批次结果文件内容为空!";
	                    	}
	                    } else {
	                    	retAts.respCode = "-1";
	                    	retAts.respInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
	                        if (StringHelper.hasAnyChar(tmpBkReader.getFirstText("/transaction/error"))) {
	                        	retAts.respInfo = tmpBkReader.getFirstText("/transaction/error");
	                        }
	                    }*/
	                } else {
	                	retAts.respCode = "-1";
	                	retAts.respInfo = tmpSbMsg.toString();
	                }
	            } else {
					retAts.respCode = "-1";
					retAts.respInfo = tmpStrRet[0];
	            }
			} else {
				retAts.respCode = "-1";
            	retAts.respInfo = "本地银行批次流水不存在，请联系银行进行咨询!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}
	
	@Override
	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return null;
	}

	@Override
	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return null;
	}
}
